<?php
/**
 * 用户行为类
 */
class User_Behavior 
{
	private static $_instance = NULL;

	/**
	 * 返回今日所有用户行为列表
	 *
	 * @return	array(
	 *	$behaviro_item,
	 *	...
	 *	)
	 *
	 * $behavior_item = array(
	 *		uid      => int,
	 *		time     => int,
	 *		shop_id  => int,
	 *		goods_id => int,
	 *		action   => string,
	 *		value    => string,
	 *	);
	 */
	public static function today ()
	{
		$today = strtotime(date('Y-m-d'));
		$search = array(
			'ctime_greater' => $today,
			'order_by'      => array('ctime' => 'DESC'),
		);

		$rs = self::instance()->search($search);	
		$result = $rs['list'];

		foreach ($result as & $r)
		{
			$r['user_name']  = user::name ($r['uid']);
			$r['shop_name']  = shop::name ($r['shop_id']);
			$r['goods_name'] = goods::name ($r['goods_id']);
			// 处理批量添加购物车的商品名称
			if (isset($r['goods_ids']) && !empty($r['goods_ids']))
			{
				$goods_ids = $r['goods_ids'];
				$goods_name_array = array();
				foreach ($goods_ids as $goods_id)
				{
					$goods_name_array[$goods_id] = goods::name($goods_id);
				}
				$r['goods_name'] = implode(' | ',$goods_name_array);
				$r['goods_name_array'] = $goods_name_array;
			}
		}

		return $result;
	}

	/**
	 * 某用户的行为数据
	 *
	 * @return array
	 */
	public function behavior ($uid, $start_time = NULL, $end_time = NULL)
	{
		if (empty($uid))
			return array();

		$search = array(
			'uid' => $uid,
			'order_by' => array('ctime' => 'DESC'),
		);

		if (!empty($start_time))
			$search['ctime_greater'] = $start_time;
		if (!empty($end_time))
			$search['ctime_less']    = $end_time;

		$rs = self::instance()->search($search);	
		$result = $rs['list'];

		foreach ($result as & $r)
		{
			$r['user_name']  = user::name ($r['uid']);
			$r['shop_name']  = shop::name ($r['shop_id']);
			$r['goods_name'] = goods::name ($r['goods_id']);
		}

		return $result;
	}

	private static function instance ()
	{
		if (self::$_instance === NULL)
		{
			self::$_instance = new Track_User();
		}

		return self::$_instance;
	}
}
